package com.cyzy.config;

import com.alibaba.fastjson2.JSON;
import com.cyzy.dto.Result;
import com.cyzy.utils.RedisUtil;
import com.cyzy.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ll
 * @version 1.0
 * @description: TODO
 * @date 2025/4/23 上午9:31
 */
@Configuration
public class AuthInterceptor implements HandlerInterceptor {
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/user/login",
            "/user/getcode"
    );
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 1.获取url
         * 2.是否白名单：放过白——》登录、注册、验证码
         * 3.不是——》需要校验
         *    1.是否有token
         *    2.是否有过期
         *    3.权限
         *
         */
        //获取url
        String url = request.getRequestURI();
        System.out.println("Intercepted URL: " + url);

        // 检查是否在白名单中
        if (WHITE_LIST.contains(url)) {
            // 如果是白名单中的 URL，直接放行
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        //获取携带的token
        // 从请求头中获取 Token
        String token = request.getHeader("Authorization");
        System.out.println(token);
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去除"Bearer "前缀
//            System.out.println(token);
            System.out.println("进行校验");
            try {
                String userAcc = TokenUtil.verifyToken(token);
                System.out.println(userAcc);
                if (redisUtil.get(token) == null) {
                    System.out.println(redisUtil.get(token));
                    System.out.println("redis的token为空");
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token已失效");
                    return false;
                }
                // 创建认证对象
//                userAccPasswordAuthenticationToken auth =
//                        new UsernamePasswordAuthenticationToken(userAcc, null, new ArrayList<>());
//                SecurityContextHolder.getContext().setAuthentication(auth);
            } catch (Exception e) {
                System.out.println("Token解析失败");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token解析失败");
                return false;
            }
        }else {
            System.out.println("无token");
            response.setHeader("content-type","text/html;charset=utf-8");
            Result result = Result.error().message("token不能为空或超时").code(401);
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
